package merisis.spindle;

import merisis.util.BitaSet;
import merisis.util.BitaSetIterator;

public class MarkCellArrangement {

	private Cell[] arrangement;
	private long touched;

	public void touch(long point) {

		if (touched <= point)
			throw new IllegalStateException("The history must be not rollback");

		this.touched = point;
		BitaSet edge = arrangement[0].points;
		edge.set(point);
	}
	
	public long snapshot() {
		
		return touched;
	}

	/**
	 * 
	 * @param productedPoints
	 *            These points should be sorted ascendingly.
	 */
	public Cell findCoreCell(long[] productedPoints, BitaSet noarranged) {

		noarranged.setAscendingPoints(productedPoints);
		
		int mscale = Integer.MAX_VALUE;
		Cell corecell = null;
		
		long point;
		BitaSetIterator itr = noarranged.iteratorInversed(0);
		CHECK_NEXT: while ((point = itr.next()) != -1) {

			Cell cell = findMinimalScaleCellOf(point);
			if (cell == null) {
				continue;
			}

			do {
				noarranged.unset(point);

				int scale = cell.getScale();
				if (cell.getScale() < mscale) {
					corecell = cell;
					mscale = scale;
				}

				long secondpoint = cell.elements[1];
				if (secondpoint == 0) {
					// signle-element cell
					continue CHECK_NEXT;
				}
				// dual-elements cell
				if (!noarranged.has(secondpoint))
					continue CHECK_NEXT; // checked already

				point = secondpoint;
				cell = findMinimalScaleCellOf(secondpoint);
			} while (cell != null);
		}

		if (corecell != null)
			return corecell;

		return arrangement[0]; // the darkest cell
	}

	public Cell findMinimalScaleCellOf(long point) {
		
		return null;
	}
}
